import * as fs from 'node:fs'
import { extname } from 'node:path'
import {
  BadRequestException,
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  ParseIntPipe,
  Post,
  Query,
  Req,
  Res,
} from '@nestjs/common'
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'
import { FastifyReply } from 'fastify'
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator'
import { definePermission, Perm } from '~/modules/admin/auth/decorators/permission.decorator'
import { AuthUser } from '~/modules/admin/auth/decorators/auth-user.decorator'

import { CreateUserDto } from './dto/create-user.dto'
import { QueryUserDto } from './dto/query-user.dto'
import { QueryUserHistoryDto } from './dto/user-history.dto'
import { UpdateUserDto } from './dto/update-user.dto'
import { UserService } from './user.service'
import { CUserEntity } from './entities/user.entity'

export const permissions = definePermission('sales:user', {
  LIST: 'list',
  CREATE: 'create',
  READ: 'read',
  UPDATE: 'update',
  DELETE: 'delete',
  IMPORT: 'import',
  EXPORT: 'export',
  HISTORY: 'history',
  QUERY: 'query',
} as const)

@ApiTags('Sales - 用户模块')
@ApiSecurityAuth()
@Controller()
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('/admin/manage/user/user-history/:id')
  @ApiOperation({ summary: '获取用户编辑历史' })
  // @Perm(permissions.HISTORY) // 暂时移除权限检查以进行测试
  @ApiResponse({
    status: 200,
    description: '获取成功',
  })
  async getUserHistory(
    @Param('id', ParseIntPipe) id: number,
    @Query() query: QueryUserHistoryDto,
    @Req() req
  ) {
    console.log(`
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ROUTE HANDLER EXECUTED: getUserHistory                    |
| Path: ${req.url}
| Method: ${req.method}
| User ID: ${id}
| Query: ${JSON.stringify(query)}
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    `);
    return this.userService.getUserHistory(id, {
      page: query.page,
      pageSize: query.pageSize
    });
  }

  @Post('/admin/manage/user')
  @ApiOperation({ summary: '新增用户' })
  @HttpCode(HttpStatus.CREATED)
  @Perm(permissions.CREATE)
  create(@Body() createUserDto: CreateUserDto, @AuthUser() user: IAuthUser) {
    // 设置createBy和updateBy为当前登录用户的ID
    createUserDto.createBy = user.uid
    createUserDto.updateBy = user.uid
    return this.userService.create(createUserDto)
  }

  @Get('/admin/manage/user')
  @ApiOperation({ summary: '获取所有用户列表' })
  @Perm(permissions.LIST)
  findAll(@Query() queryDto: QueryUserDto) {
    return this.userService.findAll(queryDto)
  }

  @Get('/admin/manage/user/:id')
  @ApiOperation({ summary: '获取用户详情' })
  @Perm(permissions.READ)
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.userService.findOne(id)
  }

  @Post('/admin/manage/user/:id')
  @ApiOperation({ summary: '更新用户' })
  @Perm(permissions.UPDATE)
  update(@Param('id', ParseIntPipe) id: number, @Body() updateUserDto: UpdateUserDto, @AuthUser() user: IAuthUser) {
    // 设置updateBy为当前登录用户的ID
    updateUserDto.updateBy = user.uid
    return this.userService.update(id, updateUserDto)
  }

  @Post('/admin/manage/user/delete/:id')
  @ApiOperation({ summary: '删除用户' })
  @Perm(permissions.DELETE)
  remove(@Param('id', ParseIntPipe) id: number) {
    console.log('===remove', id)
    return this.userService.remove(id)
  }

  @Get('/admin/manage/user/new/user-id')
  @ApiOperation({ summary: '获取新的用户ID' })
  @ApiResponse({ status: 200, description: '获取成功' })
  getNewUserId() {
    return this.userService.getNewUserId()
  }

  @Post('/admin/manage/user/import')
  @ApiOperation({ summary: '导入用户' })
  @Perm(permissions.IMPORT)
  async importUsers(@Req() request, @AuthUser() user: IAuthUser) {
    try {
      // Fastify下通过multipart获取文件
      const data = await request.file()

      if (!data) {
        throw new BadRequestException('Please upload a CSV file')
      }

      if (data.mimetype !== 'text/csv') {
        throw new BadRequestException('Only CSV files are allowed')
      }

      // 确保目录存在
      const uploadDir = './uploads/temp'
      if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true })
      }

      // 生成文件名
      const randomName = Array.from({ length: 32 })
        .fill(null)
        .map(() => Math.round(Math.random() * 16).toString(16))
        .join('')
      const filename = `${randomName}${extname(data.filename)}`
      const filepath = `${uploadDir}/${filename}`

      // 写入文件
      const writeStream = fs.createWriteStream(filepath)
      await new Promise<void>((resolve, reject) => {
        data.file.pipe(writeStream)
          .on('finish', resolve)
          .on('error', reject)
      })

      // 处理导入
      const fileData = {
        path: filepath,
        originalname: data.filename,
        mimetype: data.mimetype,
      }

      const result = await this.userService.importUsers(fileData, user.uid)
      return {
        success: true,
        ...result,
      }
    }
    catch (error) {
      throw new BadRequestException(error.message)
    }
  }

  @Get('/admin/manage/user/export')
  @ApiOperation({ summary: '导出用户' })
  @Perm(permissions.EXPORT)
  async exportUsers(@Query() queryDto: QueryUserDto, @Res() reply: FastifyReply) {
    const csvData = await this.userService.exportUsers(queryDto)

    reply.header('Content-Type', 'text/csv')
    reply.header('Content-Disposition', 'attachment; filename=users.csv')

    return reply.send(csvData)
  }
}
